package com.gitee.wsl.serialization

import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.descriptors.serialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder
import kotlin.io.encoding.Base64
import kotlin.io.encoding.ExperimentalEncodingApi

typealias Base64ByteArrayP = @Serializable(with = Base64ByteArraySerializer::class) ByteArray?

typealias HexByteArrayP = @Serializable(with = HexByteArraySerializer::class) ByteArray?

 object Base64ByteArraySerializer : KSerializer<ByteArray> {
    override val descriptor: SerialDescriptor = serialDescriptor<ByteArray>()

    @OptIn(ExperimentalEncodingApi::class)
    override fun deserialize(decoder: Decoder): ByteArray = Base64.decode(decoder.decodeString())

    @OptIn(ExperimentalEncodingApi::class)
    override fun serialize(encoder: Encoder, value: ByteArray) {
        encoder.encodeString(Base64.encode(value))
    }
}

object HexByteArraySerializer : KSerializer<ByteArray> {
    override val descriptor: SerialDescriptor = serialDescriptor<ByteArray>()

    @OptIn(ExperimentalStdlibApi::class)
    override fun deserialize(decoder: Decoder): ByteArray = decoder.decodeString().hexToByteArray()

    @OptIn(ExperimentalStdlibApi::class)
    override fun serialize(encoder: Encoder, value: ByteArray) {
        encoder.encodeString(value.toHexString())
    }
}